/*
 * 版权所有 (c) 2022-2099 TBIT。保留所有权利。
 */

/*
 * 版权所有 (c) 2022-2099 TBIT。保留所有权利。
 */

package com.tbit.main.service.impl;


import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tbit.Version;
import com.tbit.main.constant.RefundLogConstant;
import com.tbit.main.constant.UqbikeManagerConfig;
import com.tbit.main.dao.capital.RefundLogDao;
import com.tbit.main.dao.core.FeeAppealDao;
import com.tbit.main.dao.core.RideLogDao;
import com.tbit.main.dao.core.UserDao;
import com.tbit.main.pojo.*;
import com.tbit.main.pojo.VO.FeeAppealVO;
import com.tbit.main.pojo.VO.RideLogVo;
import com.tbit.main.service.FeeAppealService;
import com.tbit.main.service.HistoryService;
import com.tbit.main.service.RefundOrderService;
import com.tbit.main.service.TokenService;
import com.tbit.main.util.MD5PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author: ShiGuang
 * @create: 2021-12-13 13:34
 * @description: 费用申诉实现类
 */
@Service
@Slf4j
public  class FeeAppealServiceImpl implements FeeAppealService {

    @Autowired
    private FeeAppealDao feeAppealDao;
    @Autowired
    private RideLogDao rideLogDao;
    @Autowired
    private RefundLogDao refundLogDao;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RefundOrderService refundOrderService;

    @Override
    public int getcount(FeeAppeal feeAppeal) {
        return feeAppealDao.getcount(feeAppeal);
    }

    @Override
    public Page<FeeAppealVO> getList(FeeAppealVO feeAppealVO) {
        IPage<FeeAppealVO> page = new Page<>(feeAppealVO.getPageNo(),feeAppealVO.getPageSize());
        return feeAppealDao.getList(page,feeAppealVO);
    }

    @Override
    public List<FeeAppeal> getListOld(FeeAppealVO feeAppealVO) {
        return feeAppealDao.getListOld(feeAppealVO);
    }

    @Override
    public FeeAppeal getDetail(String orderNO,Integer accountId,Integer mapType) {
        FeeAppeal feeAppeal = feeAppealDao.getDetail(orderNO, accountId);
        RideLog rideLog = rideLogDao.getByOrderNO(orderNO);
        List<RefundLog> refundLogS = refundLogDao.getRefundLog(orderNO);
        RefundLog refundLog = null;
        double sumMoney = 0.0;
        if (refundLogS != null && refundLogS.size() > 0){
            refundLog = refundLogS.get(0);
        }
        sumMoney = refundLogS.stream().filter(x -> x.getChangeType() == RefundLogConstant.REFUND_OF_CYCLING_EXPENSES || x.getChangeType() == RefundLogConstant.USER_PENALTY_REFUND)
                .mapToDouble(RefundLog::getChangeMoney) // 假设 getAmountField 是获取金额的方法
                .sum();
        sumMoney = sumMoney/100;
        RideLogVo  rideLogVo = new RideLogVo();
        BeanUtils.copyProperties(rideLog,rideLogVo);
        rideLogVo.setMoney(rideLog.getMoney()/100);
        if (rideLog != null){
            User byUserId = userDao.getByUserId(rideLog.getUserId());
            rideLogVo.setUserName(byUserId.getName());
            rideLogVo.setUserPhone(byUserId.getPhone());
            List<TerPosition> byMachineNOAndTime = historyService.getByMachineNOAndTime(mapType, rideLog.getMachineNO(), rideLog.getStartTime(), rideLog.getEndTime(),rideLog.getMachineId());
            if (byMachineNOAndTime != null && byMachineNOAndTime.size() > 0 ){
                TerPosition terPositionStart = byMachineNOAndTime.get(0);
                TerPosition terPositionLast = byMachineNOAndTime.get(byMachineNOAndTime.size() - 1);
                rideLogVo.setStartLon(terPositionStart.getLon());
                rideLogVo.setStartLat(terPositionStart.getLat());
                rideLogVo.setStartLonC(terPositionStart.getLonC());
                rideLogVo.setStartLatC(terPositionStart.getLatC());
                rideLogVo.setEndLon(terPositionLast.getLon());
                rideLogVo.setEndLat(terPositionLast.getLat());
                rideLogVo.setEndLonC(terPositionLast.getLonC());
                rideLogVo.setEndLatC(terPositionLast.getLatC());
            }

            List<RefundOrder> refundOrders = refundOrderService.getByBusinessNo(rideLog.getOrderNO());
            Integer refundStatus = refundOrders.stream().filter(refundOrder -> Objects.equals(refundOrder.getRefundStatus(), 0))
                    .findAny()
                    .map(status -> 0)
                    .orElse(null);
            feeAppeal.setRefundStatus(refundStatus);
        }
        feeAppeal.setRideLog(rideLogVo);
        feeAppeal.setRefundedMoney(sumMoney);
        return feeAppeal;
    }

    @Override
    public RideLogDetailsVO getByOrderId(String orderId) {
        String url = UqbikeManagerConfig.managersite + "/rideLogDetails/getByOrderId.do";
//        String url = "http://127.0.0.1:60002" + "/rideLogDetails/getByOrderId.do";
        long date = System.currentTimeMillis();
        String param = "youqu";
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("orderId", orderId);
        requestBody.put("date", date);
        requestBody.put("param", param);
        requestBody.put("sign", MD5PasswordUtil.MD5("TBIT" + date + param));
        RideLogDetailsVO rideLogDetailsVO = null;
        String response = null;
        try {
            log.info("调用管理端获取工单处理界面==={}", JSON.toJSONString(requestBody));
            response = HttpRequest.post(url)
                    .header("U-APP-VERSION", Version.VERSION)
                    .body(JSON.toJSONString(requestBody))
                    .execute().body();
            log.info("调用管理端结束,返回:{}", JSON.toJSONString(response));

            //返回数据转为map
            JSONObject jsonObject = JSON.parseObject(response);
            rideLogDetailsVO =  JSONObject.parseObject(jsonObject.get("data").toString(),RideLogDetailsVO.class);
        } catch (Exception e) {
            log.error("调用管理端处理申诉工单失败:{}", e);
            log.error("调用管理端处理申诉工单失败,入参:{},返回:{}", JSON.toJSONString(requestBody), JSON.toJSONString(response));
        }
        return rideLogDetailsVO;
    }

    @Override
    public Map<String,Object> getresult(String token,FeeAppeal feeAppeal) {
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        AccountUser accountUser = tokenService.getAccount(token);
        String url = UqbikeManagerConfig.managersite + "/orderAppeal/getresult.do";
//        String url = "http://127.0.0.1:60002" + "/orderAppeal/getresult.do";
        long date = System.currentTimeMillis();
        String param = "youqu";
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("feeAppeal", feeAppeal);
        requestBody.put("accountUser", accountUser);
        requestBody.put("date", date);
        requestBody.put("param", param);
        requestBody.put("sign", MD5PasswordUtil.MD5("TBIT" + date + param));
        Boolean flag = false;
        String text = null;
        String response = null;
        try {
            log.info("调用管理端获取罚款==={}", JSON.toJSONString(requestBody));
            response = HttpRequest.post(url)
                    .header("U-APP-VERSION", Version.VERSION)
                    .body(JSON.toJSONString(requestBody))
                    .execute().body();
            log.info("调用管理端结束,返回:{}", JSON.toJSONString(response));

            //返回数据转为map
            JSONObject jsonObject = JSON.parseObject(response);
            flag =  JSONObject.parseObject(jsonObject.get("data").toString(), Boolean.class);
            text = (String) jsonObject.get("text");
            stringObjectHashMap.put("flag",flag);
            if (text == null && !flag){
                text = "请联系管理员";
            }
            stringObjectHashMap.put("text",text);
        } catch (Exception e) {
            log.error("调用管理端处理申诉工单失败:{}", e);
            log.error("调用管理端处理申诉工单失败,入参:{},返回:{}", JSON.toJSONString(requestBody), JSON.toJSONString(response));
        }
        return stringObjectHashMap;
    }
}